﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using OnlineFamilyCalendar.Common.Configuration;
using OnlineFamilyCalendar.Common.Security;

namespace OnlineFamilyCalendar.UI.Web.AuthenticationModule
{
    public class Authentication
    {
        private static OnlineFamilyCalendarAuthenticationSection _config;

        static Authentication()
        {
            _config = (OnlineFamilyCalendarAuthenticationSection)ConfigurationManager.GetSection("onlineFamilyCalendarAuthentication");
        }

        public static void RedirectFromLoginPage(OnlineFamilyCalendarIdentity identity)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpCookie authCookie = new HttpCookie(_config.CookieName, SerializeIdentity(identity));
            HttpCookie secureCookie = HttpSecureCookie.Encode(authCookie);
            secureCookie.Expires = DateTime.Now.AddMinutes(_config.CookieExpiration);
            response.Cookies.Add(secureCookie);
            response.Redirect(_config.RedirectUrl, true);
        }

        public static void Logout()
        {
            HttpCookie secureCookie = HttpContext.Current.Request.Cookies[_config.CookieName];
            if (secureCookie != null)
            {
                secureCookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(secureCookie);             
            }
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath + _config.LoginUrl, true);
        }

        public static string SerializeIdentity(OnlineFamilyCalendarIdentity identity)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, identity);
            return Convert.ToBase64String(memoryStream.ToArray());
        }

        public static OnlineFamilyCalendarIdentity DeserializeIdentity(string serializedIdentity)
        {
            byte[] bytes = Convert.FromBase64String(serializedIdentity);
            MemoryStream memoryStream = new MemoryStream(bytes);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            return binaryFormatter.Deserialize(memoryStream) as OnlineFamilyCalendarIdentity;
        }
    }
}
